<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="90%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="点位名称" prop="pointName">
                        <el-input v-model="ruleForm.pointName" class="w100p" clearable placeholder="请输入点位名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="巡查点编号" prop="pointCode">
                        <el-input v-model="ruleForm.pointCode" class="w100p" clearable
                            placeholder="请输入巡查点编号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="latitude">
                        <el-input @change="handleLatLng" v-model="ruleForm.latitude" class="w100p" clearable
                            placeholder="请选择点位"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input @change="handleLatLng" v-model="ruleForm.longitude" class="w100p" clearable
                            placeholder="请选择点位"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="误差范围" prop="errorRange">
                        <el-input @change="handleLatLng" v-model="ruleForm.errorRange" class="w100p" clearable
                            placeholder="请输入误差范围"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="w100p mapContent" v-loading="mapLoading">
                <baidu-map :center="mapCenter" :zoom="mapZoom" :scroll-wheel-zoom="true" map-type="BMAP_HYBRID_MAP"
                    @click="handleMapClick" style="height: 100%; width: 100%;" @ready="handler">
                    <bm-marker v-for="(marker, index) in markers" :key="index" :position="marker.position"></bm-marker>
                    <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
                    <bm-control>
                        <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                            <el-input v-model="keyword" type="text" placeholder="请输入地名关键字"
                                style="width: 300px;margin: 10px;" clearable>
                                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            </el-input>
                        </bm-auto-complete>
                    </bm-control>
                </baidu-map>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import mapPoint from '@/api/basic-info-manage/map-point';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        }
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            mapLoading: false,
            map: null,
            baiduMap: null,
            keyword: '',
            locations: {},
            mapCenter: { lng: 116.404, lat: 39.915 }, // 设置地图中心点坐标（经度，纬度）  
            mapZoom: 19, // 设置地图缩放级别  
            markers: [],// 用于存放地图上的标记点，
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                pointName: [
                    { required: true, message: '请输入点位名称', trigger: 'change' }
                ],
                pointCode: [
                    { required: true, message: '请输入点位编号', trigger: 'change' }
                ],
                latitude: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                longitude: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                errorRange: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
            }
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm();
                this.addEditApi = mapPoint.add;
                this.addEditName = '添加';
                this.markers = [];
                this.geolocation();
                this.$set(this.ruleForm, 'errorRange', 50);
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = mapPoint.edit
                this.addEditName = '编辑';
                this.mapLoading = true;
                setTimeout(() => {
                    this.mapLoading = false;
                    this.handleLatLng();
                }, 1500)
            }
        },
        handler({ BMap, map }) {
            this.map = map;
            this.baiduMap = BMap;
            if (this.addEditFlag == 'add') {
                this.geolocation();
            }
        },
        geolocation() {
            if (!this.baiduMap) return;
            const geolocation = new this.baiduMap.Geolocation()
            geolocation.getCurrentPosition((res) => {
                this.locations.lng = res.point.lng;
                this.locations.lat = res.point.lat;
                console.log(this.locations)
                this.$set(this.ruleForm, 'longitude', res.point.lng);
                this.$set(this.ruleForm, 'latitude', res.point.lat);
                this.markers = [{ position: { ...res.point } }];
                this.centerAndZoom(res.point)
            })
        },
        handleLatLng() {
            let marker = {
                lng: this.ruleForm.longitude,
                lat: this.ruleForm.latitude
            }
            this.markers = [{ position: { ...marker } }];// 将点击的坐标添加到标记点数组中  
            this.centerAndZoom(marker);
        },
        centerAndZoom(marker) {
            if (marker.lng && marker.lat) {
                let point = new this.baiduMap.Point(marker.lng, marker.lat)
                this.map.centerAndZoom(point, 19);
            }
        },
        handleMapClick(e) {
            const { lng, lat } = e.point; // 获取点击的经纬度  
            this.markers = [{ position: { lng, lat } }];// 将点击的坐标添加到标记点数组中  
            this.$set(this.ruleForm, 'longitude', lng);
            this.$set(this.ruleForm, 'latitude', lat);
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (!this.ruleForm.errorRange) this.ruleForm.errorRange = 50;
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.msg || msg)
                        res.success && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.mapContent {
    width: 100%;
    height: 600px;
}

::v-deep .el-dialog {
    margin-top: 30px !important;
}
</style>